package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import org.joda.time.Days;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.bean.actsupfirstcharge;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.active.module.actcontrol.activeControl;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.AreaModule;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.timeline.Timeline;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ActiveModule_超值首冲 extends PlayerModule {

    // bean ------------------------------------
    public static final int acttype = 1;

    private int payexp;
    private int payamounts; // 充值金额 单位分
    private ArrayList<Integer> type1rewardids = new ArrayList<>(); // type 1 奖励id
    private DateTime type1updatetime;
    private ArrayList<GetTimeInfo> type2gettimeinfos = new ArrayList<>();
    private HashMap<String, DateTime> groupbuytimemap;

    public int getPayexp() {
        return payexp;
    }

    public void setPayexp(int payexp) {
        this.payexp = payexp;
    }

    public int getPayamounts() {
        return payamounts;
    }

    public void setPayamounts(int payamounts) {
        this.payamounts = payamounts;
    }

    public ArrayList<Integer> getType1rewardids() {
        return type1rewardids;
    }

    public void setType1rewardids(ArrayList<Integer> type1rewardids) {
        this.type1rewardids = type1rewardids;
    }

    public DateTime getType1updatetime() {
        return type1updatetime;
    }

    public void setType1updatetime(DateTime type1updatetime) {
        this.type1updatetime = type1updatetime;
    }

    public ArrayList<GetTimeInfo> getType2gettimeinfos() {
        return type2gettimeinfos;
    }

    public void setType2gettimeinfos(ArrayList<GetTimeInfo> type2gettimeinfos) {
        this.type2gettimeinfos = type2gettimeinfos;
    }

    public HashMap<String, DateTime> getGroupbuytimemap() {
        return groupbuytimemap;
    }

    public void setGroupbuytimemap(HashMap<String, DateTime> groupbuytimemap) {
        this.groupbuytimemap = groupbuytimemap;
    }

    public class GetTimeInfo {
        private int id;
        private DateTime updatetime;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public DateTime getUpdatetime() {
            return updatetime;
        }

        public void setUpdatetime(DateTime updatetime) {
            this.updatetime = updatetime;
        }
    }

    // fun ----------------------------------------------

    /**
     * 增加充值经验
     *
     * @param topupexp
     */
    public void addtopupexp(int topupexp, int payamount) {
        int allexp = getPayexp() + topupexp;
        int allpayamount = getPayamounts() + payamount;
        Map<String, actsupfirstcharge> asfcmap = ActDataCenter.getAllData(actsupfirstcharge.class, getPlayerCode());
        for (String key : asfcmap.keySet()) {
            actsupfirstcharge asfc = asfcmap.get(key);
            int paycondition = asfc.getChargecondition();
            if (allpayamount >= paycondition) {
                int group = asfc.getGroup();
                if (!getGroupbuytimemap().containsKey(String.valueOf(group))) {
                    getGroupbuytimemap().put(String.valueOf(group), DateTime.now());
                }
            }
        }
        setPayexp(allexp);
        setPayamounts(allpayamount);
        this.set();
    }

    /**
     * 刷新
     *
     * @param tl
     */
    public void refresh(Timeline tl) {
        setTimeline(tl);
        setPayexp(0);
        setPayamounts(0);
        setType1rewardids(new ArrayList<Integer>());
        setType1updatetime(null);
        setType2gettimeinfos(new ArrayList<GetTimeInfo>());
        setGroupbuytimemap(new HashMap<String, DateTime>());
        setType2gettimeinfos(new ArrayList<GetTimeInfo>());
        set();
    }

    /**
     * @param pcode
     * @param control
     * @return
     */
    public static ActiveModule_超值首冲 create(String pcode, activeControl control) {
        if (!control.running()) {
            return null;
        }

        ActiveModule_超值首冲 am = new ActiveModule_超值首冲();
        am.setPlayerCode(pcode);
        am.setTimeline(control.getTimeline());
        am.setPayexp(0);
        am.setPayamounts(0);
        am.setType1rewardids(new ArrayList<Integer>());
        am.setType1updatetime(null);
        am.setType2gettimeinfos(new ArrayList<GetTimeInfo>());
        am.setGroupbuytimemap(new HashMap<String, DateTime>());

        am.set();
        return am;
    }

//	public static final int canget = 1;
//	public static final int hadget = 2;
//	public static final int cannotget = 3;

    public boolean haveopen(DateTime now) {
        HashMap<String, DateTime> gbtmap = getGroupbuytimemap();
        DateTime dt = new DateTime();

        if (gbtmap == null) {
            return true;
        }

        for (String key : gbtmap.keySet()) {
            DateTime dt2 = gbtmap.get(key);
            if (dt2 == new DateTime(0)) {
                return true;
            }
            if (dt == null) {
                dt = dt2;
            }
            if (dt2.isAfter(dt)) {
                dt = dt2;
            }
        }

        DateTime dttemp = dt.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
        DateTime nowtemp = now.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);

        if (Days.daysBetween(dttemp, nowtemp).getDays() < 7) {
            return true;
        }

        return false;
    }

    public int cangainreward(int id, actsupfirstcharge data) {

        int group = data.getGroup();
        DateTime buytime = getGroupbuytimemap().get(String.valueOf(group));
        if (buytime == null) {
            return DrawStatus.cannotget.getStatus();
        }

        DateTime now = DateTime.now();
        int days = ActiveUtil.days(buytime, now) + 1;
        int num = data.getNum();

        if (days < num) {
            return DrawStatus.cannotget.getStatus();
        }

        if (data.getType() == 1) {
            ArrayList<Integer> type1s = getType1rewardids();
            if (!type1s.contains(data.getId())) {
                return DrawStatus.canget.getStatus();
            } else {
                return DrawStatus.hadget.getStatus();
            }
        }

        if (data.getType() == 2) {
            ArrayList<GetTimeInfo> gettimes = getType2gettimeinfos();
            if (gettimes == null) {
                return DrawStatus.canget.getStatus();
            }

            boolean have = false;
            for (GetTimeInfo gettimeinfo : gettimes) {
                if (id != gettimeinfo.getId()) {
                    continue;
                }
                have = true;
                DateTime updatetime = gettimeinfo.getUpdatetime();
                int bndays = ActiveUtil.days(buytime, now) + 1;
                if (bndays <= 7) {
                    int unday = ActiveUtil.days(updatetime, now);
                    if (unday >= 1) {
                        return DrawStatus.canget.getStatus();
                    } else {
                        return DrawStatus.hadget.getStatus();
                    }
                } else {
                    return DrawStatus.hadget.getStatus();
                }
            }

            if (!have) {
                return DrawStatus.canget.getStatus();
            }
        }

        return DrawStatus.cannotget.getStatus();
    }

    /**
     * 能否领取奖励
     *
     * @param groupid
     * @return
     */
    public boolean cangainreward(int groupid) {
        HashMap<String, DateTime> gbtmap = getGroupbuytimemap();

        Map<String, actsupfirstcharge> map = ActDataCenter.getAllData(actsupfirstcharge.class, getPlayerCode());

        for (String key : map.keySet()) {
            actsupfirstcharge data = map.get(key);

            int group = data.getGroup();
            if (groupid != group) {
                continue;
            }

//			int condition = data.getCondition();
//			int group = data.getGroup();
            DateTime buytime = gbtmap.get(String.valueOf(group));
            if (buytime == null) {
                continue;
            }

            DateTime now = DateTime.now();
            int days = ActiveUtil.days(buytime, now) + 1;
            int num = data.getNum();

            if (days < num) {
                continue;
            }

            if (data.getType() == 1) {
                ArrayList<Integer> type1s = getType1rewardids();
                if (!type1s.contains(data.getId())) {
                    return true;
                }
            }

            if (data.getType() == 2) {
                ArrayList<GetTimeInfo> gettimes = getType2gettimeinfos();
                boolean have = false;
                for (GetTimeInfo gettimeinfo : gettimes) {
                    int id = gettimeinfo.getId();
                    if (id != data.getId()) {
                        continue;
                    }
                    have = true;
                    DateTime updatetime = gettimeinfo.getUpdatetime();
                    int bndays = ActiveUtil.days(buytime, now) + 1;
                    if (bndays <= 7) {
                        int unday = ActiveUtil.days(updatetime, now);
                        if (unday >= 1) {
                            return true;
                        }
                    }
                }

                if (!have) {
                    return true;
                }

            }
        }

        return false;
    }

    /**
     * 获取奖励
     *
     * @param pcode
     * @param groupid
     * @return
     */
    public ArrayList<Currency> gainreward(String pcode, int groupid) {
        HashMap<String, DateTime> gbtmap = getGroupbuytimemap();
        ArrayList<Currency> curs = new ArrayList<Currency>();
        Map<String, actsupfirstcharge> map = ActDataCenter.getAllData(actsupfirstcharge.class, getPlayerCode());

        for (String key : map.keySet()) {
            actsupfirstcharge data = map.get(key);

            int group = data.getGroup();
            if (groupid != group) {
                continue;
            }

//			int condition = data.getCondition();
            DateTime buytime = gbtmap.get(String.valueOf(group));
            if (buytime == null) {
                continue;
            }

            DateTime now = DateTime.now();
            int days = ActiveUtil.days(buytime, now) + 1;
            int num = data.getNum();

            if (days < num) {
                continue;
            }

            if (data.getType() == 1) {
                ArrayList<Integer> type1s = getType1rewardids();
                if (!type1s.contains(data.getId())) {
                    curs.addAll(Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum()));
                    getType1rewardids().add(data.getId());
                    setType1updatetime(DateTime.now());
//					return true;
                }
            }

            if (data.getType() == 2) {
                ArrayList<GetTimeInfo> gettimes = getType2gettimeinfos();
                boolean nohave = true;

                for (GetTimeInfo gettimeinfo : gettimes) {
                    int id = gettimeinfo.getId();
                    if (id != data.getId()) {
                        continue;
                    }
                    nohave = false;
                    DateTime updatetime = gettimeinfo.getUpdatetime();
                    int bndays = ActiveUtil.days(buytime, now) + 1;
                    if (bndays <= 7) {
                        int unday = ActiveUtil.days(updatetime, now);
                        if (unday >= 1) {
                            curs.addAll(Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum()));
                            gettimeinfo.setUpdatetime(DateTime.now());
//							return true;
                        }
                    }
                }

                if (nohave) {
                    GetTimeInfo gettimeinfo = new GetTimeInfo();
                    curs.addAll(Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum()));
                    gettimeinfo.setId(data.getId());
                    gettimeinfo.setUpdatetime(DateTime.now());
                    gettimes.add(gettimeinfo);
                }

            }
        }

        this.set();
        return curs;
    }

    public void update() {
        AreaBean ab = AreaModule.area(getPlayerCode());
        activeControl control = activeControl.getAreaOneActionInfo(ab.getAreaId(), String.valueOf(acttype));
        if (control == null) {
            return;
        }

        if (!control.running() && running()) {
            setTimeline(control.getTimeline());
            set();
        }

        if (control.running() && !running()) {
            reset(control.getTimeline());
        }

    }

    private void reset(Timeline tl) {
        refresh(tl);
    }

    // redis ---------------------------------------------------------

    static private String key(String playerCode) {
        return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
    }

    public void set() {
        try {
            setv(key(getPlayerCode()), this);
            check();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 ActiveModule_超值首冲
     *
     * @param playerCode
     * @return
     */
    static public ActiveModule_超值首冲 get(String playerCode, Boolean isNewPlayer) {
        try {
            ActiveModule_超值首冲 module = getv(key(playerCode));
            //新用户不需要去查数据库
            if (module == null && !isNewPlayer) {
                module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_超值首冲.class);
                if (module != null) {
                    module.set();
                }//同步到redis
            }

            if (module == null) {
                AreaBean ab = AreaModule.area(playerCode);
                activeControl control = activeControl.get(String.valueOf(ab.getAreaId()), String.valueOf(acttype));
                if (control != null) {
                    module = create(playerCode, control);
                }
            }
            if (module == null) {
                return null;
            }

            module.update();
            module.check();
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查看是否有可领取奖励 控制红点
     */
    public void check() {
        int type1size = 0;
        ArrayList<Integer> groups = new ArrayList<Integer>();
        Map<String, actsupfirstcharge> actscmap = ActDataCenter.getAllData(actsupfirstcharge.class, getPlayerCode());
        if (!running()) {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
            return;
        } else {
            for (String key : actscmap.keySet()) {
                actsupfirstcharge data = actscmap.get(key);
                if (!groups.contains(data.getGroup())) {
                    groups.add(data.getGroup());
                }
                if (data.getType() == 1) {
                    type1size++;
                }
            }
            if (getType1rewardids().size() == type1size) {
                new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.领完了);
            } else {
                new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
            }
        }

        for (int group : groups) {
            if (cangainreward(group)) {
                new TipHandle().updateTip(getPlayerCode(), TipType.活动_超值首充奖励, true);
                return;
            }
        }
        new TipHandle().updateTip(getPlayerCode(), TipType.活动_超值首充奖励, false);
    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                ActiveModule_超值首冲 activeModule_超值首冲 = getv(key(playerCode));
                MySQLCacheDAO.setV(key, activeModule_超值首冲);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }
    // lock==========================================================================

    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }
}
